﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XJE.Scheduler.IService;
using XJay.DB.Model;
using XJay.Scheduler.Model.Birthday.Export;
using XJay.Scheduler.Model.Birthday.Import;
using XJay.Scheduler.Model.Page;
using XJay.Scheduler.Common.Helper.Page;
using XJay.Scheduler.Model;
using XJay.Scheduler.Common.CustomException;

namespace XJay.Scheduler.Service
{
    public class BirthdayServer : IBirthdayServer
    {
        private readonly ISqlSugarClient _sqlSugarClient;
        public BirthdayServer(ISqlSugarClient sqlSugarClient)
        {
            _sqlSugarClient = sqlSugarClient;
        }
        public async Task<bool> AddBirthdayAsync(AddBirthdayParam param, UserInfoAccessor  userInfoAccessor)
        {

            var email = await _sqlSugarClient.Queryable<User>().Where(p => p.UID == userInfoAccessor.UID).Select(p => p.Email).FirstAsync();
            if (email == null) throw new XJayException("当前用户没有绑定邮箱");

            return  await _sqlSugarClient.Insertable(new App_BirthdayMail() { 
                Addressee = email,
                Name = param.Name,
                TemplateID = 1,
                CreateTime = DateTime.Now,
                UID = userInfoAccessor.UID
            }).ExecuteCommandAsync() > 0;
        }

        public async Task<bool> DeleteBirthdayAsync(int id, UserInfoAccessor userInfoAccessor)
        {
            return await _sqlSugarClient.Deleteable<App_BirthdayMail>(p=>p.EID == id && p.UID == userInfoAccessor.UID).ExecuteCommandAsync() > 0;
        }

        public async Task<PageResult<QueryBirthdayDto>> QueryBirthdayAsync(PageParam pageParam, UserInfoAccessor userInfoAccessor)
        {
            RefAsync<int> total = 0;
            return await _sqlSugarClient.Queryable<App_BirthdayMail>().Where(p=> p.UID == userInfoAccessor.UID).Select(p=>new QueryBirthdayDto() { 
                    Addressee =p.Addressee,
                    Age = p.Age,
                    Name = p.Name,
                    SendTime = p.SendTime,
                    Sex = p.Sex
            }).ToPageResultAsync(pageParam);
        }
    }
}
